import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

import '../../common/index.dart';

class LoginController extends GetxController {
  late final TextEditingController username_controller;
  late final TextEditingController password_controller;

  // 按钮动画状态
  final login_button_scale = 1.0.obs;
  final apple_button_scale = 1.0.obs;
  final terms_scale = 1.0.obs;
  final privacy_scale = 1.0.obs;

  LoginController();

  // 设置按钮缩放
  void set_login_button_scale(double scale) {
    login_button_scale.value = scale;
  }

  void set_apple_button_scale(double scale) {
    apple_button_scale.value = scale;
  }

  void set_terms_scale(double scale) {
    terms_scale.value = scale;
  }

  void set_privacy_scale(double scale) {
    privacy_scale.value = scale;
  }

  _init_data() {
    update(["login"]);
  }

  void onTap() {}

  @override
  void onInit() {
    super.onInit();
    username_controller = TextEditingController();
    password_controller = TextEditingController();
  }

  @override
  void onReady() {
    super.onReady();
    _init_data();
  }

  @override
  void onClose() {
    username_controller.dispose();
    password_controller.dispose();
    super.onClose();
  }

  void handle_login() {
    if (username_controller.text.isEmpty || password_controller.text.isEmpty) {
      SmartDialogHelper.show_warning('please fill in all fields');
      return;
    }

    final result = UserService().login_user(
      username_controller.text,
      password_controller.text,
    );

    if (result) {
      Storage().set_bool(Constants.login_status, true);
      Storage().set_string(Constants.current_user, username_controller.text);

      RouteUtil.go(RouteNames.main);
    } else {
      SmartDialogHelper.show_error('username or password is incorrect');
    }
  }

  //计算质数
  bool is_prime(int n) {
    if (n <= 1) return false;
    for (int i = 2; i * i <= n; i++) {
      if (n % i == 0) return false;
      i++;
    }
    return true;
  }

  Future<void> handle_apple_login() async {
    try {
      // 请求苹果登录凭证
      final credential = await SignInWithApple.getAppleIDCredential(
        scopes: [
          AppleIDAuthorizationScopes.email,
          AppleIDAuthorizationScopes.fullName,
        ],
      );

      // 获取用户信息
      String username =
          credential.givenName ??
          credential.userIdentifier?.substring(0, 10) ??
          '';

      // 使用苹果账户的唯一标识作为密码
      final password = credential.userIdentifier ?? '';

      // 创建用户模型
      final user = UserModel(
        id: credential.userIdentifier ?? DateTime.now().toString(),
        avatar_image: AssetsImages.avatar,
        name: username,
        password: password,
        signature: "Apple user",
        is_vip: false,
        plant_list: [],
        water_lists: [],
        like_lists: [],
        post_lists: [],
      );

      // 注册或登录
      final bool isRegister = await UserService().register_user(user);
      if (isRegister) {
        // 新用户注册成功，使用苹果账户信息登录
        final result = UserService().login_user(username, password);

        if (result) {
          // 登录成功后，跳转到主页
          RouteUtil.go(RouteNames.main);

          SmartDialogHelper.show_success('Apple login successful!');
        } else {
          SmartDialogHelper.show_error('User authentication failed');
        }
      } else {
        // 用户已存在，获取已存在用户的信息进行登录
        final existingUser = UserService().get_user_data_by_username(username);
        if (existingUser != null) {
          await UserService().login_user(username, existingUser.password ?? '');
          SmartDialogHelper.show_success('welcome back!');
        } else {
          SmartDialogHelper.show_error('user authentication failed');
        }
      }
    } catch (e) {
      SmartDialogHelper.show_error('Apple login failed: ${e.toString()}');
    }
  }
}
